<template>
  <view class="forget-container">
    <!-- 顶部背景 -->
    <view class="forget-background"></view>

    <!-- 忘记密码卡片 -->
    <view class="forget-card">
      <view class="forget-title">重置密码</view>

      <!-- 步骤指示器 -->
      <view class="step-indicator">
        <view
          class="step-item"
          :class="{ active: currentStep >= 1, done: currentStep > 1 }"
        >
          <view class="step-number">1</view>
          <view class="step-label">验证身份</view>
        </view>
        <view class="step-line" :class="{ active: currentStep > 1 }"></view>
        <view
          class="step-item"
          :class="{ active: currentStep >= 2, done: currentStep > 2 }"
        >
          <view class="step-number">2</view>
          <view class="step-label">设置新密码</view>
        </view>
        <view class="step-line" :class="{ active: currentStep > 2 }"></view>
        <view class="step-item" :class="{ active: currentStep >= 3 }">
          <view class="step-number">3</view>
          <view class="step-label">完成</view>
        </view>
      </view>

      <!-- 第一步：验证身份 -->
      <view class="step-content" v-if="currentStep === 1">
        <!-- 手机号输入 -->
        <view class="form-item">
          <text class="iconfont icon-shouji"></text>
          <input
            type="number"
            v-model="formData.mobile"
            placeholder="请输入手机号"
            maxlength="11"
          />
        </view>
        <view class="input-error" v-if="errors.mobile">{{ errors.mobile }}</view>

        <!-- 图形验证码 -->
        <view class="form-item">
          <text class="iconfont icon-yanzhengma"></text>
          <input
            type="text"
            v-model="formData.imgCode"
            placeholder="请输入图形码"
            maxlength="4"
          />
          <image
            class="img-code"
            :src="imgCodeUrl"
            @click="refreshImgCode"
            mode="aspectFit"
          ></image>
        </view>
        <view class="input-error" v-if="errors.imgCode">{{ errors.imgCode }}</view>

        <!-- 短信验证码 -->
        <view class="form-item">
          <text class="iconfont icon-yanzhengma"></text>
          <input
            type="number"
            v-model="formData.verifyCode"
            placeholder="请输入短信验证码"
            maxlength="6"
          />
          <view
            class="verify-code-btn"
            :class="{ disabled: countdown > 0 || isSendingCode }"
            @click="getVerifyCode"
          >
            <text v-if="isSendingCode" class="loading-icon"></text>
            <text v-else>{{ countdown > 0 ? `${countdown}s` : "获取验证码" }}</text>
          </view>
        </view>
        <view class="input-error" v-if="errors.verifyCode">{{ errors.verifyCode }}</view>

        <!-- 下一步按钮 -->
        <view
          class="action-btn"
          :class="{ disabled: !isStep1Valid }"
          @click="validateStep1"
          >下一步</view
        >
      </view>

      <!-- 第二步：设置新密码 -->
      <view class="step-content" v-if="currentStep === 2">
        <!-- 新密码输入 -->
        <view class="form-item">
          <text class="iconfont icon-mima"></text>
          <input
            v-if="showPassword"
            class="form-input"
            type="text"
            v-model="formData.newPassword"
            placeholder="请输入新密码"
            maxlength="20"
          />
          <input
            v-if="!showPassword"
            class="form-input"
            type="password"
            v-model="formData.newPassword"
            placeholder="请输入新密码"
            maxlength="20"
            :password="true"
          />
          <text
            class="iconfont"
            :class="showPassword ? 'icon-xianshimima' : 'icon-buxianshimima'"
            @click="showPassword = !showPassword"
            style="padding: 0 0 0 20px"
          ></text>
        </view>
        <view class="password-tips"
          >密码长度为6-20位，可以是数字或字母或字母与数字组合</view
        >
        <view class="input-error" v-if="errors.newPassword">{{
          errors.newPassword
        }}</view>

        <!-- 确认密码输入 -->
        <view class="form-item">
          <text class="iconfont icon-mima"></text>
          <input
            v-if="showConfirmPassword"
            class="form-input"
            type="text"
            v-model="formData.confirmPassword"
            placeholder="请再次输入新密码"
            maxlength="20"
          />
          <input
            v-if="!showConfirmPassword"
            class="form-input"
            type="password"
            v-model="formData.confirmPassword"
            placeholder="请再次输入新密码"
            maxlength="20"
            :password="true"
          />
          <text
            class="iconfont"
            :class="showConfirmPassword ? 'icon-xianshimima' : 'icon-buxianshimima'"
            @click="showConfirmPassword = !showConfirmPassword"
            style="padding: 0 0 0 20px"
          ></text>
        </view>
        <view class="input-error" v-if="errors.confirmPassword">{{
          errors.confirmPassword
        }}</view>

        <!-- 提交按钮 -->
        <view v-if="!isStep2Valid || isSubmitting" class="action-btn disabled">
          <text :class="[isSubmitting ? 'loading-spinner' : '']">{{
            !isSubmitting ? "确认修改" : ""
          }}</text>
        </view>
        <view v-else class="action-btn" @click="resetPassword">
          <text>确认修改</text>
        </view>
      </view>

      <!-- 第三步：完成 -->
      <view class="step-content success-content" v-if="currentStep === 3">
        <view class="success-icon">✓</view>
        <view class="success-title">密码重置成功</view>
        <view class="success-desc">您的密码已经重置，请使用新密码登录</view>

        <!-- 返回登录按钮 -->
        <view class="action-btn" @click="goToLogin">返回登录</view>
      </view>

      <!-- 返回登录链接 -->
      <view class="login-link" v-if="currentStep < 3">
        <text @click="goToLogin">返回登录</text>
      </view>
    </view>

    <!-- 底部文本 -->
    <view class="forget-footer">沃客薪服 · 渠道服务平台</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentStep: 1, // 当前步骤：1-验证身份，2-设置新密码，3-完成
      formData: {
        mobile: "", // 手机号
        imgCode: "", // 图形验证码
        imgKey: "", // 图形验证码key
        verifyCode: "", // 短信验证码
        smsToken: "",
        newPassword: "", // 新密码
        confirmPassword: "", // 确认密码
      },
      errors: {
        mobile: "",
        imgCode: "",
        verifyCode: "",
        newPassword: "",
        confirmPassword: "",
      },
      showPassword: false, // 显示密码
      showConfirmPassword: false, // 显示确认密码
      imgCodeUrl: "", // 图形验证码URL
      countdown: 0, // 验证码倒计时
      timer: null, // 定时器
      isSendingCode: false, // 发送验证码状态
      isSubmitting: false, // 提交状态
    };
  },
  computed: {
    // 验证手机号是否有效
    isValidMobile() {
      return /^1[3-9]\d{9}$/.test(this.formData.mobile);
    },

    // 第一步表单是否有效
    isStep1Valid() {
      return (
        this.isValidMobile &&
        this.formData.imgCode.length === 4 &&
        this.formData.verifyCode.length === 6
      );
    },

    // 第二步表单是否有效
    isStep2Valid() {
      return (
        this.validatePassword(this.formData.newPassword) &&
        this.formData.newPassword === this.formData.confirmPassword
      );
    },
  },
  onLoad() {
    // 加载图形验证码
    this.refreshImgCode();
  },
  onUnload() {
    // 清除定时器
    this.clearCountdownTimer();
  },
  methods: {
    // 刷新图形验证码
    refreshImgCode() {
      // 生成随机key
      this.formData.img_key = Date.now() + Math.random().toString(36).substr(2, 10);

      // 发送POST请求获取base64图片
      this.$request.getImgCode(
        {
          key: this.formData.img_key,
          type: "base64",
        },
        (res) => {
          console.log("验证码返回:", res);
          this.imgCodeUrl = res.data.image;
        }
      );
    },

    // 清除倒计时定时器
    clearCountdownTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // 验证密码规则
    validatePassword(password) {
      // 验证密码规则：6-20位，可以是数字或字母或字母与数字组合
      return /^[A-Za-z0-9]{6,20}$/.test(password);
    },

    // 获取短信验证码
    getVerifyCode() {
      // 重置错误信息
      this.errors.mobile = "";
      this.errors.imgCode = "";
      this.errors.verifyCode = "";

      if (!this.isValidMobile) {
        uni.showToast({
          title: "请输入有效的手机号",
          icon: "none",
          mask: true,
          duration: 1500,
        });
        return;
      }
      if (this.formData.imgCode.trim().length != 4) {
        uni.showToast({
          title: "请输入4位数的图形码",
          icon: "none",
          mask: true,
          duration: 1500,
        });
        return;
      }

      // 倒计时中或正在发送时不能重复获取
      if (this.countdown > 0 || this.isSendingCode) {
        return;
      }

      // 验证手机号
      if (!this.formData.mobile) {
        this.errors.mobile = "请输入手机号";
        return;
      }

      if (!this.isValidMobile) {
        this.errors.mobile = "手机号格式不正确";
        return;
      }

      // 验证图形验证码
      if (!this.formData.imgCode) {
        this.errors.imgCode = "请输入图形验证码";
        return;
      }

      // 设置发送状态
      this.isSendingCode = true;

      // 发送请求
      this.$request.getSmsCode(
        {
          mobile: this.formData.mobile,
          scenario: "6", // 1员工注册登录 2渠道注册登录 3发薪确认 4变更员工手机号 5变更渠道手机号 6渠道忘记密码
        },
        (res) => {
          this.formData.smsToken = res.sms_token;
          // 提示成功
          uni.showToast({
            title: "验证码已发送",
            icon: "success",
          });

          // 开始倒计时
          this.startCountdown();
        },
        (err) => {
          // 刷新图形验证码
          this.refreshImgCode();
        },
        () => {
          // 重置发送状态
          this.isSendingCode = false;
        }
      );
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60;
      this.clearCountdownTimer(); // 先清除可能存在的定时器

      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          this.clearCountdownTimer();
        }
      }, 1000);
    },

    // 验证第一步
    validateStep1() {
      // 重置错误信息
      this.errors.mobile = "";
      this.errors.imgCode = "";
      this.errors.verifyCode = "";

      let isValid = true;

      // 验证手机号
      if (!this.formData.mobile) {
        this.errors.mobile = "请输入手机号";
        isValid = false;
      } else if (!this.isValidMobile) {
        this.errors.mobile = "手机号格式不正确";
        isValid = false;
      }

      // 验证图形验证码
      if (!this.formData.imgCode) {
        this.errors.imgCode = "请输入图形验证码";
        isValid = false;
      } else if (this.formData.imgCode.length !== 4) {
        this.errors.imgCode = "请输入4位图形验证码";
        isValid = false;
      }

      // 验证短信验证码
      if (!this.formData.verifyCode) {
        this.errors.verifyCode = "请输入短信验证码";
        isValid = false;
      } else if (this.formData.verifyCode.length !== 6) {
        this.errors.verifyCode = "请输入6位短信验证码";
        isValid = false;
      }

      if (!isValid) {
        return;
      }

      // 发送请求验证身份
      this.$request.verifyCode(
        {
          mobile: this.formData.mobile,
          sms_code: this.formData.verifyCode,
          sms_token: this.formData.smsToken,
          // img_code: this.formData.imgCode,
          // img_key: this.formData.imgKey,
          // type: 'reset_password' // 标识是忘记密码场景
        },
        (res) => {
          // 验证通过，进入下一步
          this.currentStep = 2;
        },
        (err) => {
          // 验证失败，刷新图形验证码
          this.refreshImgCode();
          // 显示错误信息
          if (err.message.includes("验证码")) {
            this.errors.verifyCode = err.message || "验证码错误";
          }
        }
      );
    },

    // 重置密码
    resetPassword() {
      // 重置错误信息
      this.errors.newPassword = "";
      this.errors.confirmPassword = "";

      let isValid = true;

      // 验证新密码
      if (!this.formData.newPassword) {
        this.errors.newPassword = "请输入新密码";
        isValid = false;
      } else if (!this.validatePassword(this.formData.newPassword)) {
        this.errors.newPassword = "密码格式不正确";
        isValid = false;
      }

      // 验证确认密码
      if (!this.formData.confirmPassword) {
        this.errors.confirmPassword = "请确认新密码";
        isValid = false;
      } else if (this.formData.newPassword !== this.formData.confirmPassword) {
        this.errors.confirmPassword = "两次输入的密码不一致";
        isValid = false;
      }

      if (!isValid || this.isSubmitting) {
        return;
      }

      // 设置提交状态
      this.isSubmitting = true;

      // 显示加载中
      uni.showLoading({
        title: "提交中...",
        mask: true,
      });

      // 发送重置密码请求
      this.$request.resetPassword(
        {
          mobile: this.formData.mobile,
          new_password: this.formData.newPassword,
          confirm_password: this.formData.confirmPassword,
        },
        (res) => {
          // 密码重置成功，进入第三步
          this.currentStep = 3;
        },
        (err) => {},
        () => {
          this.isSubmitting = false;
        }
      );
    },

    // 返回登录页面
    goToLogin() {
      uni.navigateTo({
        url: "/pages/login",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/static/scss/variables.scss";
.forget-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f5f5f5;
  position: relative;

  /* 顶部背景 */
  .forget-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 400rpx;
    background: linear-gradient(to bottom, $colorPrimary, $colorPrimaryLight);
    border-radius: 0 0 50% 50% / 0 0 20% 20%;
    z-index: 1;
  }

  /* 忘记密码卡片 */
  .forget-card {
    position: relative;
    width: 90%;
    margin-top: 180rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.1);
    padding: 60rpx 40rpx;
    z-index: 2;

    .forget-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 50rpx;
    }

    /* 步骤指示器 */
    .step-indicator {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 60rpx;

      .step-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        position: relative;

        .step-number {
          width: 50rpx;
          height: 50rpx;
          line-height: 50rpx;
          text-align: center;
          background-color: #eee;
          color: #999;
          border-radius: 50%;
          font-size: 28rpx;
          font-weight: bold;
          margin-bottom: 10rpx;
          transition: all 0.3s;
        }

        .step-label {
          font-size: 24rpx;
          color: #999;
          transition: all 0.3s;
        }

        &.active {
          .step-number {
            background-color: $colorPrimary;
            color: #fff;
          }

          .step-label {
            color: $colorPrimary;
            font-weight: bold;
          }
        }

        &.done {
          .step-number {
            background-color: #34c759;
            color: #fff;
          }

          .step-label {
            color: #34c759;
          }
        }
      }

      .step-line {
        width: 100rpx;
        height: 2rpx;
        background-color: #eee;
        margin: 0 10rpx;
        margin-bottom: 35rpx;
        transition: all 0.3s;

        &.active {
          background-color: #34c759;
        }
      }
    }

    /* 表单样式 */
    .step-content {
      .form-item {
        display: flex;
        align-items: center;
        height: 110rpx;
        border-bottom: 1rpx solid #eee;
        margin-bottom: 30rpx;

        .iconfont {
          font-size: 40rpx;
          color: $colorPrimary;
          margin-right: 20rpx;
        }

        input {
          flex: 1;
          height: 100%;
          font-size: 28rpx;
        }

        .img-code {
          width: 300rpx;
          height: 100rpx;
          background-color: #f5f5f5;
          border-radius: 8rpx;
        }

        .verify-code-btn {
          width: 220rpx;
          height: 70rpx;
          line-height: 70rpx;
          text-align: center;
          color: #fff;
          font-size: 24rpx;
          background-color: $colorPrimary;
          border-radius: 35rpx;
          display: flex;
          justify-content: center;
          align-items: center;

          .loading-icon {
            display: inline-block;
            width: 30rpx;
            height: 30rpx;
            border: 2rpx solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 0.8s linear infinite;
          }

          &.disabled {
            background-color: #ccc;
          }
        }
      }

      .password-tips {
        font-size: 24rpx;
        color: #999;
        margin-top: -20rpx;
        margin-bottom: 20rpx;
        padding-left: 60rpx;
      }

      .input-error {
        font-size: 24rpx;
        color: #ff3b30;
        margin-top: -20rpx;
        margin-bottom: 20rpx;
        padding-left: 60rpx;
      }

      /* 按钮样式 */
      .action-btn {
        width: 100%;
        height: 90rpx;
        line-height: 90rpx;
        text-align: center;
        color: #fff;
        font-size: 32rpx;
        font-weight: bold;
        background-color: $colorPrimary;
        border-radius: 45rpx;
        margin-top: 40rpx;
        margin-bottom: 30rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        &.disabled {
          background-color: #ccc;
        }

        .loading-spinner {
          display: inline-block;
          width: 30rpx;
          height: 30rpx;
          border: 3rpx solid rgba(255, 255, 255, 0.3);
          border-radius: 50%;
          border-top-color: #fff;
          animation: spin 0.8s linear infinite;
        }
      }
    }

    /* 成功页面样式 */
    .success-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 30rpx 0;

      .success-icon {
        width: 120rpx;
        height: 120rpx;
        line-height: 120rpx;
        text-align: center;
        background-color: #34c759;
        color: #fff;
        border-radius: 50%;
        font-size: 60rpx;
        margin-bottom: 30rpx;
      }

      .success-title {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
      }

      .success-desc {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 60rpx;
        text-align: center;
      }
    }

    /* 登录链接 */
    .login-link {
      text-align: center;
      font-size: 26rpx;
      color: $colorPrimary;

      text {
        padding: 10rpx;
      }
    }
  }

  /* 底部文本 */
  .forget-footer {
    position: fixed;
    bottom: 60rpx;
    font-size: 24rpx;
    color: #999;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
